import OpenAI from 'openai'
import { CONFIG } from './config'

// 定义消息类型
export type Message = {
	role: 'system' | 'user' | 'assistant'
	content: string
}

// 定义请求选项类型
export type RequestOptions = {
	model?: string
	temperature?: number
	max_tokens?: number
	stream?: boolean
}

export interface DeepSeekChatCompletionChunk {
	id: string
	object: string
	created: number
	model: string
	system_fingerprint: string
	choices: {
		index: number
		delta: {
			content: string
		}
	}[]
}

export interface DeepSeekConvertChunk {
    id: string
    content: string
    created: number
}

/**
 * Deepseek API 客户端
 * 支持流式和非流式输出
 */
export class DeepseekClient {
	private client: OpenAI

	constructor() {
		this.client = new OpenAI({
			apiKey: CONFIG.DEEPSEEK_API_KEY,
			baseURL: CONFIG.DEEPSEEK_API_BASE_URL,
		})
	}

	/**
	 * 发送非流式请求
	 * @param messages 消息数组
	 * @param options 请求选项
	 * @returns 响应文本
	 */
	async chat(messages: Message[], options: RequestOptions = {}): Promise<string> {
		try {
			const response = await this.client.chat.completions.create({
				model: options.model || CONFIG.DEEPSEEK_API_MODEL,
				messages,
				temperature: options.temperature ?? 0.7,
				max_tokens: options.max_tokens,
				stream: false,
			})

			return response.choices[0]?.message.content || ''
		} catch (error) {
			console.error('Deepseek API 请求失败:', error)
			throw error
		}
	}

	/**
	 * 发送流式请求
	 * @param messages 消息数组
	 * @param options 请求选项
	 * @param onChunk 接收流式响应的回调函数
	 */
	async chatStream(
		messages: Message[],
		options: RequestOptions = {},
		onChunk: (chunk: DeepSeekConvertChunk) => void,
	): Promise<void> {
		try {
			const stream = await this.client.chat.completions.create({
				model: options.model || CONFIG.DEEPSEEK_API_MODEL,
				messages,
				temperature: options.temperature ?? 0.7,
				max_tokens: options.max_tokens,
				stream: true,
			})

			for await (const chunk of stream) {
				const content = chunk.choices[0]?.delta.content || ''
				if (content) {
					onChunk({
						id: chunk.id,
						content,
						created: chunk.created,
					})
				}
			}
		} catch (error) {
			console.error('Deepseek API 流式请求失败:', error)
			throw error
		}
	}
}
